<template>
  <div>
    <!-- 直接上传版 -->
    <layout title="配置视频" :footer="false" description="横版 16:9, 1920*1080，竖版  9:16 1080*1920">
      <a-upload
        action="/baiduapi/batch/uploadOneVideo"
        :headers="{'Authori-zation': token}"
        name="video"
        list-type="picture-card"
        :file-list="fileList"
        multiple
        @change="handleChange"
        @preview="handlePreview"
      >
        <div v-if="fileList.length <= limit">
          <a-icon type="plus" />
          <div class="ant-upload-text"> 上传 </div>
        </div>
      </a-upload>
    </layout>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <div id="myVideo"></div>
    </a-modal>
  </div>
</template>

<script>
import layout from '../layout'

// function getPic(url){
  // 获取视频封面图
  // return new Promise(function (resolve) {
  //   let dataURL = "";
  //   const video = document.createElement("video");
  //   video.setAttribute("crossOrigin", "anonymous"); // 处理跨域
  //   if(process.env.NODE_ENV === 'production'){
  //     var curPath=window.document.location.href;  
  //     var pathName=window.document.location.pathname;  
  //     var pos=curPath.indexOf(pathName);  
  //     var localhostPaht=curPath.substring(0,pos);
  //     url = url.replace('http://bdapi.eie.cn',localhostPaht)
  //     // if(localhostPaht.indexOf('turing') != -1){
  //       // url = url.replace('http://','https://').replace('bdapi', 'turing')
  //     // }
  //   }else{  
  //     url = url.replace('https://','').replace('http://','').replace('bdapi.eie.cn', '/bdapiUpload')
  //   }
  //   // console.log(url)
  //   video.setAttribute("src", url);
  //   video.setAttribute("preload", "auto");
  //   video.addEventListener("loadeddata", function () {
  //     const canvas = document.createElement("canvas");
  //     const width = video.videoWidth || 0; // canvas的尺寸和图片一样
  //     const height = video.videoHeight || 0; // 设置默认宽高为  400  240
  //     let w,h,x,y; // w,h 为需求图片的宽高， x、y为坐标
  //     if(width > height){ // 横版
  //       w = 960;
  //       h = 540;
  //       x = (1140 - 960)/2;
  //       y = (640 - 540)/2
  //     }else if(width < height){ // 竖版
  //       w = 540;
  //       h = 720;
  //       x = (640 - 540)/2;
  //       y = (1140 - 720)/2
  //     }
  //     // console.log(w,h,x,y)
  //     canvas.width = w;
  //     canvas.height = h;
  //     canvas.getContext("2d").drawImage(video, -x, -y, width, height); // 绘制canvas
  //     dataURL = canvas.toDataURL("image/jpeg"); // 转换为base64
  //     resolve({dataURL,url});
  //   });
  // });
// }

export default {
  data() {
    return {
      limit: 99999,
      fileList:[],
      previewImage:'',
      previewVisible:false,
      list:[],
      timeOut:null,
      taskList:[],

      errorNum:0,
      errorTimeout:null,
    }
  },
  methods:{
    async beforeUpload(file){
      // console.log(file)
      if(!(file.type === 'video/mp4')){
        this.$message.error('只能上传mp4文件')
        return Promise.reject()
      }else if(file.size > 100*1024*1000){
        // this.$message.error('视频文件超过100mb')
        this.setMessage()
        return Promise.reject()
      }
      return Promise.resolve()
    },
    async handlePreview(file) {
      // console.log(file)
      // 解决video无法重新更新视频的bug
      this.previewVisible = true;
      this.$nextTick(()=>{
      //   <video id="myVideo" style="width: 100%" controls >
      // </video>
        let video = document.createElement("video")
        video.controls = true
        video.width = 478
        let sourceDom = document.createElement("source")
        sourceDom.src = file.preview
        let myVideo = document.getElementById('myVideo')
        video.appendChild(sourceDom)
        myVideo.appendChild(video)
        this.previewImage = file.preview;
      })
    },
    async handleChange(e){
      // console.log(e)
      // 操作视图
      if(e.file.size > 100*1024*1000){
        this.setMessage()
        return false
      }
      if(e.file.status == 'uploading' && e.file.type == 'video/mp4'){
        this.fileList.push({
          name: e.file.name,
          uid: e.file.uid,
          url: e.file.url || null,
          preview: e.file.preview || null,
          status: e.file.status
        })
      }else if(e.file.status == 'done' && e.file.response?.errcode == 0){
        // let itemFileList = e.fileList.find(o=>o.uid == e.file.uid)
        // let data = e.file.response.data
        // getPic(data.fileurl).then((e)=>{ // 视频抽帧
        //   console.log(e)
        //   itemFileList.url = e.dataURL
        //   itemFileList.preview = e.url
        //   itemFileList.status = 'done'
        // }).catch(()=>{

        // })
      }

      // 操作输出的值,并获取真实的 fileList 数组
      let list = []
      let fileList = []
      if(e.fileList.length > 0){
        for(let item of e.fileList){
          if(item.status == 'done' && item.response?.errcode == 0){
            let data = item.response.data
            list.push(data)
          }
          let itemFileList = this.fileList.find(o=>o.uid == item.uid)
          if(itemFileList){
            if(item.status == "error"){
              itemFileList.response = '上传失败'
            }
            fileList.push(itemFileList)
          }
        }
      }
      this.list = list
      this.fileList = fileList
      this.$emit('update:form', this.list)
    },
    setMessage(){
      this.errorNum++
      if(this.errorTimeout){clearTimeout(this.errorTimeout)}
      this.errorTimeout = setTimeout(() => {
        this.$message.error('有'+this.errorNum+'个视频文件超过100mb')
        this.errorNum == 0
      }, 200);
    }
  },
  watch:{
    previewVisible(val){
      if(!val){
        // 清除video中的内容
        let myVideo = document.getElementById('myVideo')
        let child = myVideo.lastElementChild
        while(child){
          myVideo.removeChild(child); 
          child = myVideo.lastElementChild; 
        }
      }
    }
  },
  computed:{
    token(){
      return this.$store.state.user.userInfo.token
    }
  },
  components:{layout},
}
</script>

<style lang="less" scoped>
.ant-tooltip{
  max-height: 305px;
  overflow: hidden;
}
</style>